/**
 *
 */
package com.jeecms.wicool.action.report;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.common.base.Strings;
import com.jeecms.cms.entity.main.CmsUser;
import com.jeecms.cms.web.CmsUtils;
import com.jeecms.wicool.domain.PeiSongDianDomain;
import com.jeecms.wicool.domain.SaleCountReportDomain;
import com.jeecms.wicool.domain.SaleDayReportDomian;
import com.jeecms.wicool.domain.SaleMoneyReportDomain;
import com.jeecms.wicool.entity.shops.DistributionAddress;
import com.jeecms.wicool.entity.util.Dictionary2;
import com.jeecms.wicool.manager.report.ReportMng;
import com.jeecms.wicool.manager.shops.DistributionAddressMng;
import com.jeecms.wicool.manager.util.DictionaryMng;
import com.jeecms.wicool.util.ExportExcel;

/**
 * @author spring
 */
@RequestMapping("/report")
public class ReportAct {

    private static final Logger logger = LoggerFactory.getLogger(ReportAct.class);

    @Autowired
    private ReportMng reportMng;

    @Autowired
    private DistributionAddressMng distributionAddressMng;
    
    @Autowired
	private DictionaryMng DicMng;

    @RequestMapping("/to_sale_count_dis_view.do")
    public String getDisReport(HttpServletRequest request, ModelMap model) {
        CmsUser user = CmsUtils.getUser(request);
        List<DistributionAddress> disAddress = distributionAddressMng.list(user.getShopId(), null, null, null);
        model.addAttribute("disAddress", disAddress);
        return "report/list_dis_report";
    }


    @RequestMapping("/to_sale_count_dis.do")
    public void getDisSaleCount(Short[] status, Integer disAddId, String startTime, String endTime, Integer typeId, HttpServletResponse response) {

        List<PeiSongDianDomain> disSaleCount = reportMng.getDisSalePrice(disAddId, startTime, endTime, typeId);
        if(disSaleCount != null && !disSaleCount.isEmpty()){
        	OutputStream out;
            try {
                String[] headers = {"编号","配送点", "商品名称", "规格","单价（元）", "数量","金额（元）"};
                String fileNameTemp = "distribute-salecount-%s.xls";
                StringBuffer timeRange = new StringBuffer("");
                if (!Strings.isNullOrEmpty(startTime)) {
                    timeRange.append(startTime + "-");
                }
                if (!Strings.isNullOrEmpty(endTime)) {
                    timeRange.append("-" + endTime);
                }

                String fileName = String.format(fileNameTemp, timeRange);
                response.setContentType("octets/stream");
                response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
                out = response.getOutputStream();
                ExportExcel<PeiSongDianDomain> ex = new ExportExcel<PeiSongDianDomain>();
                ex.exportExcel(headers, disSaleCount, out, "yyyy-MM-dd HH:mm:ss");
                out.close();
            } catch (IOException e) {
                logger.error("getDisSaleCount error.", e);
            }
        }
    }


    @RequestMapping("/to_sale_money_dis_view.do")
    public String getDisSaleMoneyView(Integer pageNo, Short[] status, Integer disAddId, String startTime, String endTime, Integer typeId, HttpServletRequest request, ModelMap model) {
        List<PeiSongDianDomain> list = reportMng.getDisSalePrice(disAddId, startTime, endTime, typeId);
        model.addAttribute("disAddId", disAddId);
        model.addAttribute("startTime", startTime);
        model.addAttribute("endTime", endTime);
        model.addAttribute("typeId", typeId);
        //model.addAttribute("status", status);
        model.addAttribute("pagination", list);
        List<DistributionAddress> disAddress = distributionAddressMng.list(null, null, null, null);
        model.addAttribute("disAddress", disAddress);

        return "report/list_dis_report";

    }


    @RequestMapping("/to_sale_money_dis.do")
    public void getDisSaleMoney(Short[] status, Integer disAddId, String startTime, String endTime, Integer typeId, HttpServletResponse response) {
        Date startTimeDate = Strings.isNullOrEmpty(startTime) ? null : DateTime.parse(startTime, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        Date endTimeDate = Strings.isNullOrEmpty(endTime) ? null : DateTime.parse(endTime, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();

        ExportExcel<SaleMoneyReportDomain> ex = new ExportExcel<SaleMoneyReportDomain>();
        List<SaleMoneyReportDomain> disSaleMoney = reportMng.getDisSalePrice(status, disAddId, startTimeDate, endTimeDate, typeId);
        OutputStream out;
        try {
            String[] headers = {"编号", "订单价格", "折减价格", "支付价格", "优惠券价格", "支付方式", "订单类型", "拼单返还价格"};
            String typeName = "all";
            if (typeId != null) {
                switch (typeId) {
                    case 0:
                        typeName = "normal";
                        break;
                    case 1:
                        typeName = "group_buy";
                        break;
                    case 2:
                        typeName = "kill_buy";
                        break;
                    case 3:
                        typeName = "vip";
                        break;
                    case 4:
                        typeName = "online_pay";
                        break;
                }
            }
            String fileNameTemp = "distribute-price-%s-(%s).xls";
            StringBuffer timeRange = new StringBuffer("");
            if (!Strings.isNullOrEmpty(startTime)) {
                timeRange.append(startTime + "-");
            }
            if (!Strings.isNullOrEmpty(endTime)) {
                timeRange.append("-" + endTime);
            }
            String fileName = String.format(fileNameTemp, typeName, timeRange);
            response.setContentType("octets/stream");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            out = response.getOutputStream();
            ex.exportExcel(headers, disSaleMoney, out, "yyyy-MM-dd HH:mm:ss");
        } catch (IOException e) {
            logger.error("getDisSaleCount error.", e);
        }
    }


    @RequestMapping("/to_sale_day_list.do")
    public String to_saledaylist(ModelMap model) {
    	SimpleDateFormat format1 = new SimpleDateFormat(
    			"yyyy-MM-dd");
        String saleDate = format1.format(new Date());
        model.addAttribute("startTime", saleDate);
        model.addAttribute("endTime", saleDate);
        List<Dictionary2> listDic3=DicMng.getList("activity_type");
        model.addAttribute("listDic3", listDic3);
        model.addAttribute("pagination", new ArrayList<Map<String, Object>>());
        return "report/list_sale_report";
    }

    @RequestMapping("/to_sale_money_report_view.do")
    public String saleDayList(Integer pageNo, String startTime, String endTime, Integer typeId, HttpServletRequest request, ModelMap model) {
        if (StringUtils.isBlank(startTime) || StringUtils.isBlank(endTime)) {
            model.addAttribute("message", "请选择销售日期");
            return "report/list_sale_report";
        }
        List<SaleDayReportDomian> pagination = reportMng.getSaleDayPrice(startTime, endTime, typeId);
        model.addAttribute("pagination", pagination);
        model.addAttribute("startTime", startTime);
        model.addAttribute("endTime", endTime);
        model.addAttribute("typeId", typeId);
        List<Dictionary2> listDic3=DicMng.getList("activity_type");
        model.addAttribute("listDic3", listDic3);
        return "report/list_sale_report";
    }


    @RequestMapping("/to_sale_count_report.do")
    public String exportExcelSaleDay(String startTime, String endTime, Integer typeId, HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        if (StringUtils.isBlank(startTime) || StringUtils.isBlank(endTime)) {
            model.addAttribute("message", "请选择销售日期");
            return "report/list_sale_report";
        }

        Date startTimeDate = Strings.isNullOrEmpty(startTime) ? null : DateTime.parse(startTime, DateTimeFormat.forPattern("yyyy-MM-dd")).toDate();
        Date endTimeDate = Strings.isNullOrEmpty(endTime) ? null : DateTime.parse(endTime, DateTimeFormat.forPattern("yyyy-MM-dd")).toDate();

        ExportExcel<SaleDayReportDomian> ex = new ExportExcel<SaleDayReportDomian>();
        List<SaleDayReportDomian> pagination = reportMng.getSaleDayPrice(startTime, endTime, typeId);

        if (pagination != null && !pagination.isEmpty()) {
            OutputStream out;
            try {
                String[] headers = {"姓名", "电话", "地址", "配送时间", "订单编号", "下单时间", "菜品信息", "是否预约订单", "订单支付类型", "订单总金额", "配送费", "是否优惠活动","优惠后订单总金额"};
                String fileNameTemp = "order-report-(%s).xls";
                StringBuffer timeRange = new StringBuffer("");
                if (!Strings.isNullOrEmpty(startTime)) {
                    timeRange.append(startTime + "-");
                }
                if (!Strings.isNullOrEmpty(endTime)) {
                    timeRange.append("-" + endTime);
                }

                String fileName = String.format(fileNameTemp, timeRange);
                response.setContentType("octets/stream");
                response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
                out = response.getOutputStream();
                ex.exportExcel(headers, pagination, out, "yyyy-MM-dd HH:mm:ss");
                out.close();
                System.out.println("excel导出成功！");
            } catch (Exception e) {
                logger.error("get_sale_count_report error.", e);
            }
        } else {
            model.addAttribute("message", "exportExcel.failed.not.have.apply");
        }
        return "report/list_sale_report";
    }


    @RequestMapping("/to_sale_money_report.do")
    public String exportExcelSaleMonth(String startTime, String endTime, Integer typeId, HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        if (StringUtils.isBlank(startTime) || StringUtils.isBlank(endTime)) {
            model.addAttribute("message", "请选择销售日期");
            return "report/list_sale_report";
        }

        ExportExcel<SaleDayReportDomian> ex = new ExportExcel<SaleDayReportDomian>();
        List<SaleDayReportDomian> pagination = reportMng.getSaleDayPrice(startTime, endTime, typeId);

        if (pagination != null && !pagination.isEmpty()) {
            OutputStream out;
            try {
                String[] headers = {"编号", "订单号", "支付总金额", "优惠劵金额", "微信支付金额", "货到付款金额", "余额支付金额","配送点","订单类型", "拼单返还价格", "订单日期"};
                String fileNameTemp = "sale-money-report-%s.xls";
                StringBuffer timeRange = new StringBuffer("");
                if (!Strings.isNullOrEmpty(startTime)) {
                    timeRange.append(startTime + "-");
                }
                if (!Strings.isNullOrEmpty(endTime)) {
                    timeRange.append("-" + endTime);
                }
                String fileName = String.format(fileNameTemp, timeRange);
                response.setContentType("octets/stream");
                response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
                out = response.getOutputStream();
                ex.exportExcel(headers, pagination, out, "yyyy-MM-dd HH:mm:ss");
                out.close();
                System.out.println("excel导出成功！");
            } catch (Exception e) {
                logger.error("get_sale_money_report error.", e);
            }
        } else {
            model.addAttribute("message", "exportExcel.failed.not.have.apply");
        }
        return "report/list_sale_report";
    }
    
    @RequestMapping("/to_score_report_view.do")
    public String saleDayList(String userName ,String mobile,String endTime,String zhuanUserName,String zhuanMobile, HttpServletRequest request, ModelMap model) {
        if (StringUtils.isBlank(endTime)) {
        	SimpleDateFormat format1 = new SimpleDateFormat(
        			"yyyy-MM-dd");
        	endTime = format1.format(new Date());
        }
        List<Map<String,Object>> list = reportMng.getUserScoreList(userName, mobile, endTime, zhuanUserName, zhuanMobile);
        model.addAttribute("list", list);
        model.addAttribute("endTime", endTime);
        model.addAttribute("userName", userName);
        model.addAttribute("mobile", mobile);
        model.addAttribute("zhuanUserName", zhuanUserName);
        model.addAttribute("zhuanMobile", zhuanMobile);
        return "report/list_score_report";
    }
    
    @RequestMapping("/v_excel_score_report_list.do")
    public String exportSaleDayList(String userName ,String mobile,String endTime,String zhuanUserName,String zhuanMobile, HttpServletRequest request,HttpServletResponse response, ModelMap model) {
        if (StringUtils.isBlank(endTime)) {
        	SimpleDateFormat format1 = new SimpleDateFormat(
        			"yyyy-MM-dd");
        	endTime = format1.format(new Date());
        }
        List<Map<String,Object>> list = reportMng.getUserScoreList(userName, mobile, endTime, zhuanUserName, zhuanMobile);
        List<ScoreBean> beanList = new ArrayList<ScoreBean>();
        for (Map<String, Object> map : list) {
        	ScoreBean bean = new ScoreBean(map.get("num"), map.get("name"), map.get("mobile"), map.get("sale_money_count"), map.get("score_count"), map.get("zhuanName"), map.get("zhuanMobile"), map.get("score_count1"));
        	beanList.add(bean);
		}
        
        if (list != null && !list.isEmpty()) {
            OutputStream out;
            try {
                String[] headers = {"编号", "用户名称", "用户电话", "用户消费汇总", "用户积分汇总", "转介绍人", "转介绍人电话", "转介绍人积分汇总"};
                String fileNameTemp = "score-report-%s.xls";
                String fileName = String.format(fileNameTemp, endTime);
                response.setContentType("octets/stream");
                response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
                out = response.getOutputStream();
                ExportExcel<ScoreBean> ex = new ExportExcel<ScoreBean>();
                ex.exportExcel(headers, beanList, out, "yyyy-MM-dd HH:mm:ss");
                out.close();
                System.out.println("excel导出成功！");
            } catch (Exception e) {
                logger.error("exportSaleDayList error.", e);
            }
        } else {
            model.addAttribute("message", "exportExcel.failed.not.have.apply");
        }
        return "report/list_score_report";
    }
    
}
